<?php
namespace Home\Controller;

use Think\Controller;

class InsertController extends Controller
{

    //-------------------------------------------------------------
    /**
     * 非签约接口
     *
     * $arg = [
     * 'mch_id',
     * 'key',
     * 'order_amount',
     * 'order_id',
     * 'name',
     * 'phone',
     * 'id_card',
     * 'bank_card',
     * //...
     * ];
     */
    public function sysData()
    {

        if (IS_POST) {

            $post = I('post.');
            $check = $this->checkData($post);

            if (!$check['status']) {
                $this->ajaxReturn($check, 'json');
            }
            $user = $this->getUser($post);
            $find_user_id = M('yh_user')->field('id')->where(['phone' => $post['phone']])->find();

            $order = $this->getOrder($post);


            M()->startTrans();

            if (!$find_user_id) {
                $uid = M('yh_user')->data($user);
            } else {
                $uid = $find_user_id;
            }

            if ($uid) {
                $order['uid'] = $uid;
                $res = M('yh_order')->add($order);
            }
            if (!empty($uid) && !empty($res)) {
                M()->commit();
                $this->ajaxReturn([
                    'status' => true,
                    'code' => '00',
                    'msg' => 'SUCCESS'
                ], 'json');

            } else {
                $usersql = M('yh_user')->getLastSql();
                $ordersql = M('yh_order')->getLastSql();
                $log = date("Y-m-d H:i:s") . '|' . $post['order_id'] . '|' . $usersql . '|' . $ordersql . '|' .
                    json_encode($post) . '\r\n';
                file_put_contents('./logs/' . date('Y-m-d') . '.log', $log, FILE_APPEND);
                M()->rollback();
                $this->ajaxReturn([
                    'status' => false,
                    'code' => '049',
                    'msg' => '数据存入出现错误'
                ], 'json');
            }
        }

        echo 'only post';
    }

    private function getOrder($post)
    {
        $order = [
            'order_amount' => $post['amount'],
            'order_status' => '0',
            'order_time' => time(),
            'order_id' => $post['order_id']
        ];
        return $order;
    }

    private function getUser($post)
    {

        $user = [
            'name' => $post['name'],
            'phone' => $post['phone'],
            'id_card' => $post['id_card'],
            'bank_card' => $post['bank_card'],
            'tag_id' => $this->getTag($post['mch_id']),
            'create_at' => time(),
            'order_token' => '接口非签约',
        ];
        return $user;
    }


    private function getTag($mch_id)
    {
        $tag_id = 3;
        switch ($mch_id) {
            case    '52621':
                $tag_id = 1;
                break;

            //...
            default:
                $tag_id = 3;

        }
        return $tag_id;
    }


    private function checkData($data)
    {
        $arg = [
            'mch_id',
            'key',
            'order_amount',
            'order_id',
            'name',
            'phone',
            'id_card',
            'bank_card',
            //...
        ];

        $data = array_filter($data);

        foreach ($data as $k => $v) {
            if (!in_array((string)$k, $arg)) {
                return [
                    'status' => false,
                    'code' => '093',
                    'msg' => '缺少必须参数'
                ];
            }
        }


        if (!$data['mch_id'] || !$data['key']) {
            return [
                'status' => false,
                'code' => '093',
                'msg' => '缺少mch_id或key'
            ];
        }
        $user = M('yh_admin')->where(['username' => $data['mch_id']])->find();
        if (!$user || !password_verify($user['password'], $user['key'])) {
            return [
                'status' => false,
                'code' => '101',
                'msg' => '身份校验失败'
            ];
        }

        return [
            'status' => true,
        ];
    }







    //-------------------------------------------------------------
    /**
     * 用户数据
     */
    public function user()
    {

        $obj = new \Org\Util\Data('./Public/logs');
        $user = $obj->getUsers();

        $count = 0;
        $all = count($user);
        $data = [];
        foreach ($user as $k => $v) {

            if ($v['phone'] == '15893755505') {

                continue;
            }

            $data = [
                'name' => $v['name'],
                'phone' => $v['phone'],
                'id_card' => $v['id_card'],
                'bank_card' => $v['bank_card'],
                'order_token' => serialize($v['order_token']),
                'create_at' => time()
            ];

            M('yh_user')->add($data);
            $count++;
        }

        echo 'total:' . $all . '---succ:' . $count;

    }

    public function tag()
    {
        $user = M('yh_user')->select();

        foreach ($user as $k => $v) {
            $mch_id = '';

            $t = unserialize($v['order_token'])[0];


            if (explode('|', $t)[0] == '订单号') {

                $orderId = explode('|', $t)[1];
                $mch_id = M('bc_orders')->field('mch_id')->where(['order_id' => $orderId])->find();

            } else if (explode('|', $t)[0] == '绑定号') {

                $d = explode('|', $t)[1];

                $mch_id = explode('-', $d)[0];


            } else if (explode('|', $t)[0] == '请求号') {

                $mch_id = M('bc_orders')->field('mch_id')->where(['out_trade_no' => explode('|', $t)[1]])->find();
            }


            switch ($mch_id) {

                case '52621':
                    $tag_id = 1;
                    break;
                case '52623':

                case '52626':

                case '52633':
                    $tag_id = 2;
                    break;
                default:
                    $tag_id = 4;
                    break;

            }


            M('yh_user')->where(['id' => $v['id']])->setField(['tag_id' => $tag_id]);
        }
        echo 'over';
    }

    /**
     * 订单表
     */
    public function order()
    {


        //start
        $obj = new \Org\Util\Data('./Public/logs');
        $orders = $obj->getSysOrder();

        $count = 0;
        $all = count($orders);

        $user = M('yh_user')->select();

        //order_token
        foreach ($user as $k => $v) {
            $user[$k]['order_token'] = unserialize($v['order_token']);
        }

        //order
        foreach ($orders as $k => $v) {
            $uid = '';
            //user
            foreach ($user as $k1 => $v1) {
                //user_token
                foreach ($v1['order_token'] as $k2 => $v2) {

                    $order_t = explode('|', $v['order_token']);

                    if (strpos($v2, $order_t[1]) > 0) {
                        $uid = $v1['id'];
                    }

                }

            }

            if (isset($v['cardByNo'])) {

                $order = M('bc_orders')->where(['order_id' => $v['pay_number']])->find();

                $data = [
                    'order_id' => $v['pay_number'],
                    'order_amount' => $v['transAmount'],
                    'order_token' => $v['order_token'],
                    'uid' => $uid,
                    'order_status' => $order['status'],
                    'order_time' => strtotime($order['created_at'])
                ];


            } else {

                $order = M('bc_orders')->where(['out_trade_no' => $v['out_trade_no']])->find();
                $orderId = $order['order_id'];
                $data = [
                    'order_id' => $orderId,
                    'order_amount' => $v['amount'],
                    'order_token' => $v['order_token'],
                    'uid' => $uid,
                    'order_status' => $order['status'],
                    'order_time' => $order['created_at']
                ];

            }

            $orderId = M('yh_order')->add($data);
            if (!empty($orderId)) {
                $count++;
            }

        }
        echo '全部数据:' . $all . '条,' . '成功数据' . $count . '条';

    }


}